// 创建模板

const pieChartTemplate = document.createElement("template");
pieChartTemplate.innerHTML = `
    <style>
        :host {
            display: block;
            width: 100%;
            height: 100%;
        }
        .chart-container {
            width: 100%;
            height: 100%;
            min-width: 300px;
            min-height: 150px;
        }
    </style>
    <div class="chart-container"></div>
`;

class PieChartComponent extends HTMLElement {
    constructor() {
        super();

        // 创建 Shadow DOM
        const shadow = this.attachShadow({ mode: 'closed' });

        // 克隆模板内容
        shadow.appendChild(pieChartTemplate.content.cloneNode(true));

        // 获取图表容器
        const chartDiv = shadow.querySelector('.chart-container');

        // 初始化定时器和图表实例
        this.timerId = null;
        this.chart = echarts.init(chartDiv);
    }

    connectedCallback() {
        // 导入工具函数（假设已从外部文件导入）
        const {buildConfig } = window.attributeUtils;

        // 定义属性清单 - 移除了xAxis、yAxis、grid相关属性，增加饼图特有属性
        const titleAttrs = [
            ['title-text_text', '销售数据统计'],
            ['title-show_radio', true],
            ['title-left_slider', 'center'],
            ['title-top_slider', ''],
            ['title-right_slider', ''],
            ['title-bottom_slider', ''],
            ['title-textalign_select', ''],
            ['title-textstyle-color_colorpicker', '#333'],
            ['title-textstyle-fontsize_number', 18],
            ['title-textstyle-fontweight_select', 'bold'],
            ['title-subtext_text', '2023年度数据'],
            ['title-subtextstyle-color_colorpicker', '#666'],
            ['title-subtextstyle-fontsize_number', 14],
            ['title-subtextstyle-fontweight_select', 'normal'],
        ];

        const legendAttrs = [
            ['legend-show_radio', true],
            ['legend-textstyle-color_colorpicker', '#666'],
            ['legend-itemstyle-color_colorpicker', 'auto'],
            ['legend-itemheight_number', 14],
            ['legend-itemwidth_number', 25],
            ['legend-bottom_number', "auto"],
            ['legend-left_number', "right"],
            ['legend-top_number', "center"],
            ['legend-orient_select', "vertical"],
            ['legend-itemgap_number', 20],
            ['legend-textstyle-fontsize_number', 12]
        ];

        const pieAttrs = [
            ['pie-radius_slider', '40%'],
            ['pie-center_array', '50%,50%'],
            ['pie-label-show_radio', true],
            ['pie-label-position_select', 'outside'],
            ['pie-label-formatter_text', '{b}: {c} ({d}%)'],
            ['pie-labelline-show_radio', true],
            ['pie-labelline-length_number', 10],
            ['pie-labelline-length2_number', 5],
        ];

        const seriesAttrs = [
            ['series-name_text', '销售额'],
            ['series-type_select', 'pie'],
            ['series-itemstyle-color_array', "#C1232B,#B5C41F,#FCCE10,#E87C25,#27727B,#FE8463"],
            ['series-emphasis-itemstyle-shadowblur_number', 10],
            ['series-emphasis-itemstyle-shadowcolor_colorpicker', 'rgba(0, 0, 0, 0.5)'],
            ['base-data-url_text', ''],
            ['base-echart-init-script_text', ''],
        ];

        // 生成 config
        const titleConfig = buildConfig(this, titleAttrs);
        const legendConfig = buildConfig(this, legendAttrs);
        const pieConfig = buildConfig(this, pieAttrs);
        const seriesConfig = buildConfig(this, seriesAttrs);

        // 如果颜色列表只有一个颜色，扩展成默认 12 个
        if (seriesConfig.itemstyleColor && seriesConfig.itemstyleColor.length <= 1) {
            seriesConfig.itemstyleColor = new Array(12).fill(seriesConfig.itemstyleColor[0] || 'blue');
        }

        // 调整初始大小
        this.resizeChart();

        // 监听 resize 事件
        window.addEventListener('resize', this.resizeChart.bind(this));
        // 观察父容器的大小变化
        if (ResizeObserver) {
            this.observer = new ResizeObserver(() => this.resizeChart());
            this.observer.observe(this.parentElement);
        }

        // 加载数据并渲染饼图
        if (seriesConfig.dataUrl) {
            fetch(seriesConfig.dataUrl)
                .then(res => res.json())
                .then(data => {
                    // 处理饼图数据
                    let pieData = [];
                    // 适配 [{ "销售": [{name: "...", value: ...}, ...] }] 格式
                    if (Array.isArray(data) && data.length > 0) {
                        const firstItem = data[0];
                        const key = Object.keys(firstItem)[0];
                        pieData = firstItem[key].map(item => ({
                            name: item.name,
                            value: item.value
                        }));
                    }

                    // 生成饼图系列配置
                    const series = [{
                        name: seriesConfig.name,
                        type: 'pie',
                        colorBy: "data",
                        radius: pieConfig.radius,
                        center: pieConfig.center,
                        data: pieData,
                        label: {
                            show: pieConfig.labelShow,
                            position: pieConfig.labelPosition,
                            formatter: pieConfig.labelFormatter
                        },
                        labelLine: {
                            show: pieConfig.labellineShow,
                            length: pieConfig.labellineLength,
                            length2: pieConfig.labellineLength2
                        },
                        itemStyle: {
                            color: params => seriesConfig.itemstyleColor[params.dataIndex % seriesConfig.itemstyleColor.length]
                        },
                        emphasis: {
                            itemStyle: {
                                shadowBlur: seriesConfig.emphasisItemstyleShadowblur,
                                shadowColor: seriesConfig.emphasisItemstyleShadowcolor
                            }
                        }
                    }];

                    // 构建饼图配置
                    const option = {
                        title: {
                            show: titleConfig.show,
                            text: titleConfig.text,
                            left: titleConfig.left,
                            right: titleConfig.right,
                            top: titleConfig.top,
                            bottom: titleConfig.bottom,
                            textAlign: titleConfig.textalign,
                            textStyle: {
                                color: titleConfig.textstyleColor,
                                fontSize: titleConfig.textstyleFontsize,
                                fontWeight: titleConfig.textstyleFontweight,
                            },
                            subtext: titleConfig.subtext,
                            subtextStyle: {
                                color: titleConfig.subtextstyleColor,
                                fontSize: titleConfig.subtextstyleFontsize,
                                fontWeight: titleConfig.subtextstyleFontweight,
                            },
                        },
                        legend: {
                            show: legendConfig.show,
                            bottom: legendConfig.bottom,
                            left: legendConfig.left,
                            top: legendConfig.top,
                            orient: legendConfig.orient,
                            itemWidth: legendConfig.itemwidth,
                            itemHeight: legendConfig.itemheight,
                            textStyle: {
                                color: legendConfig.textstyleColor,
                                fontSize: legendConfig.textstyleFontsize
                            },
                            itemStyle: {
                                color: legendConfig.itemstyleColor
                            },
                            itemGap: legendConfig.itemgap,
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b}: {c} ({d}%)'
                        },
                        series: series
                    };

                    console.log("初始化默认值配置项：" + JSON.stringify(option))
                    this.chart.setOption(option);
                })
                .catch(error => {
                    console.error('加载饼图数据失败:', error);
                });
        }

        // 执行外部初始化脚本
        if (seriesConfig.echartInitScript) {
            try {
                eval(seriesConfig.echartInitScript);
            } catch (e) {
                console.error('执行初始化脚本错误:', e);
            }
        }
    }

    // 监听的属性列表
    static get observedAttributes() {
        console.log("饼图监听属性："+ getAttributesByType('pie'))
        return window.getAttributesByType('pie');
    }

    // 组件断开连接时清理资源
    disconnectedCallback() {
        // 移除 resize 事件监听器
        window.removeEventListener('resize', this.resizeChart.bind(this));

        // 停止观察父容器的大小变化
        if (this.observer) {
            this.observer.disconnect();
        }

        // 清除定时器
        clearInterval(this.timerId);
    }

    // 设置定时器
    setTimer(interval) {
        // 清除之前的定时器
        clearInterval(this.timerId);
        if (interval > 0) {
            this.timerId = setInterval(() => {
                this.executeScript();
            }, interval);
        }
    }

    // 执行脚本
    executeScript() {
        if (this.echarttimerscript !== "") {
            try {
                eval(this.echarttimerscript);
            } catch (error) {
                console.log(error.message);
            }
        } else {
            console.log("no script to execute");
        }
    }

    // 调整图表大小
    resizeChart() {
        this.chart.resize();
    }

    // 获取图表实例
    getChartInstance() {
        return this.chart;
    }

    // 更新数据
    async updateData(dataurl) {
        try {
            const fullUrl = dataurl;
            const response = await fetch(fullUrl);
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            const data = await response.json();
            if (data) {

// 处理饼图数据
                let pieData = [];
                // 适配 [{ "销售": [{name: "...", value: ...}, ...] }] 格式
                if (Array.isArray(data) && data.length > 0) {
                    const firstItem = data[0];
                    const key = Object.keys(firstItem)[0];
                    pieData = firstItem[key].map(item => ({
                        name: item.name,
                        value: item.value
                    }));
                    this.chart.setOption({
                        series: [{
                            data: pieData
                        }]
                    });
                }
            }
        } catch (error) {
            console.log(`错误: ${error.message}`);
        }
    }

    // 属性变化时更新图表
    attributeChangedCallback(name, oldValue, newValue) {
        console.log("回调接收的原始参数：", {
            name: name,
            nameType: typeof name,
            nameLength: name.length, // 空字符串时为 0
            oldValue: oldValue,
            newValue: newValue
        });
        if (name) {
            const currentOptions = this.chart.getOption();
            if (!currentOptions) return;

            switch (name) {
                case 'title-show_radio':
                    var showBool = newValue === "true";
                    // 更新X轴数据
                    currentOptions.title[0].show = showBool;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;

                case 'title-text_text':
                    currentOptions.title[0].text = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;

                case 'title-textstyle-color_colorpicker':
                    // 更新X轴数据
                    currentOptions.title[0].textStyle.color = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;

                case 'title-textstyle-fontsize_number':
                    // 更新X轴数据
                    currentOptions.title[0].textStyle.fontSize = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'title-textstyle-fontweight_select':
                    // 更新X轴数据
                    currentOptions.title[0].textStyle.fontSize = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;

                case 'title-subtext_text':
                    // 更新X轴数据
                    currentOptions.title[0].subtext = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'title-subtextstyle-fontsize_number':
                    // 更新X轴数据
                    currentOptions.title[0].subtextStyle.fontSize = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'title-subtextstyle-fontweight_select':
                    // 更新X轴数据
                    currentOptions.title[0].subtextStyle.fontWeight = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;

                case 'title-left_slider':
                    // 更新
                    currentOptions.title[0].left = `${newValue}%`;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'title-top_slider':
                    // 更新
                    currentOptions.title[0].top = `${newValue}%`;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'title-right_slider':
                    currentOptions.title[0].right = `${newValue}%`;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'title-bottom_slider':
                    currentOptions.title[0].bottom = `${newValue}%`;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'title-itemgap_number':
                    currentOptions.title[0].itemGap = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'title-textalign_select':
                    currentOptions.title[0].textAlign = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'grid-left_slider':
                    currentOptions.series[0].left = `${newValue}%`;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'grid-right_slider':
                    currentOptions.series[0].right = `${newValue}%`;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'grid-bottom_slider':
                    currentOptions.series[0].bottom = `${newValue}%`;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'grid-top_slider':
                    currentOptions.series[0].top = `${newValue}%`;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'legend-show_radio':
                    var showBool = newValue === "true";
                    // 图例的显示
                    currentOptions.legend[0].show = showBool;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'legend-textstyle-color_colorpicker':
                    // 更新X轴数据
                    currentOptions.legend[0].textStyle.color = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'legend-textstyle-fontsize_number':
                    // 获取当前值
                    currentOptions.legend[0].textStyle.fontSize = newValue;
                    // 获取当前值
                    this.chart.setOption(currentOptions);
                    break;
                case 'legend-textstyle-fontweight_select':
                    // 获取当前值
                    currentOptions.legend[0].textStyle.fontWeight = newValue;
                    // 获取当前值
                    this.chart.setOption(currentOptions);
                    break;
                case 'legend-textstyle-fontstyle_select':
                    // 获取当前值
                    currentOptions.legend[0].textStyle.fontStyle = newValue;
                    this.chart.setOption(currentOptions);
                    break;
                case 'legend-itemstyle-color_colorpicker':
                    // 获取当前值
                    currentOptions.legend[0].itemStyle.color = newValue;
                    this.chart.setOption(currentOptions);
                    break;
                case 'legend-itemheight_number':
                    // 获取当前值
                    currentOptions.legend[0].itemHeight = parseInt(newValue);
                    this.chart.setOption(currentOptions);
                    break;
                case 'legend-itemwidth_number':
                    // 获取当前值
                    currentOptions.legend[0].itemWidth = parseInt(newValue);
                    this.chart.setOption(currentOptions);
                    break;
                case 'legend-bottom_number':
                    // 获取当前值
                    currentOptions.legend[0].bottom = `${newValue}%`;
                    this.chart.setOption(currentOptions);
                    break;
                case 'legend-top_number':
                    // 获取当前值
                    currentOptions.legend[0].top = `${newValue}%`;
                    this.chart.setOption(currentOptions);
                    break;
                case 'legend-right_number':
                    // 获取当前值
                    currentOptions.legend[0].right = `${newValue}%`;
                    this.chart.setOption(currentOptions);
                    break;
                case 'legend-itemgap_number':
                    // 获取当前值
                    currentOptions.legend[0].itemGap = parseInt(newValue);
                    this.chart.setOption(currentOptions);
                    break;
                case 'series-itemstyle-color_array':
                    var newValue_array = newValue.split(",");
                    if (newValue_array.length>0){
                        if (currentOptions.series.length > 0){
                            // 更新颜色配置
                            currentOptions.series[0].itemStyle.color = function(params) {
                                return newValue_array[params.dataIndex];
                            };
                            // 设置新的选项
                            this.chart.setOption(currentOptions);
                        }

                    }
                    break;
                case 'pie-label-show_radio':
                    var showBool = newValue === "true";
                    // 图例的显示
                    currentOptions.series[0].label.show = showBool;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'pie-label-position_select':
                    // 图例的显示
                    currentOptions.series[0].label.position = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'pie-label-formatter_text':
                    // 图例的显示
                    currentOptions.series[0].label.formatter = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'pie-radius_slider':
                    // 图例的显示
                    currentOptions.series[0].radius = newValue;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'pie-labelline-show_radio':
                    var showBool = newValue === "true";
                    // 图例的显示
                    currentOptions.series[0].labelLine.show = showBool;
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'pie-labelline-length_number':
                    // 图例的显示
                    currentOptions.series[0].labelLine.length = parseInt(newValue);
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;
                case 'pie-labelline-length2_number':
                    // 图例的显示
                    currentOptions.series[0].labelLine.length2 = parseInt(newValue);
                    // 设置新的选项
                    this.chart.setOption(currentOptions);
                    break;

                case 'echart-timer':
                    this.setTimer(parseInt(newValue) * 1000);
                    break;

                case 'echart-timer-script':
                    if (this.echarttimerscript === "") {
                        clearInterval(this.timerId);
                    } else {
                        this.setTimer(parseInt(this.echarttimer) * 1000);
                    }
                    break;

                case 'echart-init-script':
                    if (this.echartinitscript !== "") {
                        try {
                            eval(this.echartinitscript);
                        } catch (error) {
                            console.log(error.message);
                        }
                    }
                    break;

                case 'base-data-url_text':
                    this.updateData(newValue);
                    break;
            }
        }
    }
}

// 定义新的 HTML 元素
customElements.define('pie-chart-component', PieChartComponent);
